﻿using ReflectionStudio.Core;
using ReflectionStudio.Core.Events;
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.OracleClient;
using System.IO;
using System.Linq;
using System.Linq.Expressions;
using System.Xml;
namespace WPFExcelReport
{
    class QFTAB50Report : BaseReport
    {
        #region ----------------PROPERTIES----------------------------------
        public OracleConnection OracleDB;
        public OracleCommand orlReadCommand = new OracleCommand();
        public IntexReptServBLClient proxy;
        private Dictionary<string, object> dicParamater;
        public DataSet dsResult;
        public DataSet setUI = new DataSet();
        string ABPAUFFKRS;
        string ABPAUFFLFD;
        string ABPAUFFPOS;
        string WBBTP;
        string DocType;
        string CellName = "";
        string CellValue = "";
        string strCompany;
        string strExcelFile;
        string Today
        {
            get
            {
                DateTime now = DateTime.Now;
                return now.Year.ToString() + Right("00" + now.Month.ToString(), 2) + Right("00" + now.Day.ToString(), 2);
            }
        }
        #endregion
        public QFTAB50Report()
            : base()
        {
        }
        public QFTAB50Report(Dictionary<string, object> dicParamater)
            : base(dicParamater)
        {
            DocType = dicParamater["DocType"].ToString().Trim();
            strCompany = dicParamater["Company"].ToString().Trim();
            strExcelFile = dicParamater["ExcelFile"].ToString().Trim();
        }
        public override void WriteExcelReport(string fileType)
        {
            bool IsFTP = false;
            try
            {

                strExcelFile = @"QFT\QFTStandard.xls";
                DataRow row = dsSource.Tables["ABPOS"].Rows[0];
                string KRS = row["ABPAUFKRS"].ToString().Trim();
                string LFD = row["ABPAUFLFD"].ToString().Trim();
                string POS = row["ABPAUFPOS"].ToString().Trim();
                long flfd = 0;
                flfd = System.Convert.ToInt64(LFD);
                string newfilename = KRS + "-" + LFD + "-" + POS;
                exAgent.CheckWorkBook(newfilename);
                LocalFile(KRS + "-" + LFD + "-" + POS);
            }
            catch (Exception ex)
            {
                Tracer.Error(ex.StackTrace, ex);
            }
        }
        private void FillInEXCEL()
        {
            try
            {
                string value = "";
                DataRow row = null;
                int x = 1, y = 1;
                x = 3; y = 5;
                row = dsSource.Tables["ABKOPF"].Rows[0];
                value = row["ABKAUFKRS"].ToString() + "-" + row["ABKAUFLFD"].ToString();
                exAgent.SetCellValue(x, y, value);

                x = 3; y = 30;
                exAgent.SetCellValue(x, y, Today);
                if (dsSource.Tables.Contains("LIEFDAT"))
                {
                    if (dsSource.Tables["LIEFDAT"].Rows.Count > 0)
                    {
                        row = dsSource.Tables["LIEFDAT"].Rows[0];
                        value = row["LSNAME1"].ToString().Trim() + row["LSNAME2"].ToString();
                        value = GetGB2312Value(value);
                        x = 4; y = 5;
                        exAgent.SetCellValue(x, y, value);
                        value = row["LSSTRASSE1"].ToString();
                        value = GetGB2312Value(value);
                        x = 5; y = 5;
                        exAgent.SetCellValue(x, y, value);
                    }
                }
                int rownum = -1;

                foreach (DataRow dwABPOS in dsSource.Tables["ABPOS"].Rows)
                {
                    rownum++;
                    string art = dwABPOS["ABPART"].ToString();
                    string var = dwABPOS["ABPVAR"].ToString();
                    string color = dwABPOS["ABPFARBE"].ToString();
                    value = dwABPOS["ABPLIEFDAT"].ToString();

                    x = 4; y = 30;
                    exAgent.SetCellValue(x, y, value);
                    value = dwABPOS["ABPFILLER1"].ToString();
                    x = 8; y = 5;
                    exAgent.SetCellValue(x, y, value);
                     
                    #region=====Technical============
                    var query = from rows in dsSource.Tables["GSDAT"].AsEnumerable()
                                where rows["GSART"].ToString() == art
                                & rows["GSVAR"].ToString() == var
                                select rows;
                    foreach (DataRow rw in query)
                    {
                        if (var.Trim() != "")
                            value = art.Trim() + "/" + var;
                        exAgent.SetCellValue(12 + rownum * 2, 3, value);
                        value = rw["GSGARNBEZ"].ToString();
                        value = GetGB2312Value(value);
                        exAgent.SetCellValue(12 + rownum * 2 + 1, 3, value.Trim());
                    }
                    #endregion
                    #region======color=======
                    query = from rows in dsSource.Tables["GSCOLOR"].AsEnumerable()
                            where rows["GSCART"].ToString() == art
                            & rows["GSCVAR"].ToString() == var
                            & rows["GSCFARBE"].ToString() == color
                            select rows;
                    foreach (DataRow rw in query)
                    {
                        exAgent.SetCellValue(12 + rownum * 2, 16, color.Trim());
                         value = rw["GSCBEZ"].ToString().Trim();
                        value = GetGB2312Value(value);
                        exAgent.SetCellValue(12 + rownum * 2 + 1, 16, value);
                        value = rw["GSCMUFRB"].ToString();
                        value = GetGB2312Value(value).Trim();
                        exAgent.SetCellValue(12 + rownum * 2, 21, value);
                    }
                    #endregion

                    #region=====composition=======
                    query = from rows in dsSource.Tables["GSMATK"].AsEnumerable()
                            where rows["GSMART"].ToString() == art
                            & rows["GSMVAR"].ToString() == var
                            select rows;
                    string composition = "";
                    foreach (DataRow rw in query)
                    {       
                        string sg = rw["GSMRBEZ"].ToString().Trim();
                        string bez = rw["GSMRSPZ"].ToString();
                        bez = GetGB2312Value(bez).Trim();
                        double ratio = System.Convert.ToDouble( rw["GSMRANT"].ToString()) * 0.1;
                        composition += ratio + "%" + sg + bez;
                    }
                    exAgent.SetCellValue(12 + rownum * 2, 11, composition);
                    #endregion

                    #region====price=======
                    /*value = dwABPOS["ABPSOLLMENGE6"].ToString();
                    value = System.Math.Round(System.Convert.ToDouble(value) * 0.01, 3).ToString() + "kg";
                    exAgent.SetCellValue(4, 27, value);*/
                    query = from rows in dsSource.Tables["ABPR"].AsEnumerable()
                            where rows["ARAUFKRS"].ToString() == dwABPOS["ABPAUFKRS"].ToString()
                            & rows["ARAUFLFD"].ToString() == dwABPOS["ABPAUFLFD"].ToString()
                            & rows["ARAUFPOS"].ToString() == dwABPOS["ABPAUFPOS"].ToString()
                            select rows;
                    double wert = 0;
                    foreach (DataRow rw in query)
                    {
                        value = rw["ARWERT"].ToString();
                        wert += System.Math.Round(System.Convert.ToDouble(value) * 0.001, 2);
                    }
                    exAgent.SetCellValue(12 + rownum * 2, 24,  wert + "元/kg");
                    #endregion
                    #region====yarn=========
                    double total = 0;
                    query = from rw in dsSource.Tables["GAAUF"].AsEnumerable()
                            where rw["GAAUFKRS"].ToString() == dwABPOS["ABPAUFKRS"].ToString()
                            & rw["GAAUFLFD"].ToString() == dwABPOS["ABPAUFLFD"].ToString()
                            & rw["GAAUFPOS"].ToString() == dwABPOS["ABPAUFPOS"].ToString()
                            & rw["GASA"].ToString() == "310"
                            select rw;
                    int count = 1;
                    count = query.Count();
                    foreach (DataRow rw in query)
                    {
                        double gakg1 = System.Convert.ToDouble(rw["GAKG1"].ToString()) * 0.01;
                        string gaart = rw["GAART"].ToString();
                        string gavar = rw["GAVAR"].ToString();
                        string gacolor = rw["GAFARBE"].ToString();
                        string yarn = gaart.Trim();
                        if (gavar.Trim() != "")
                            yarn += "/" + gavar.Trim();
                        if (gacolor.Trim() != "")
                        {
                            if (gacolor != "000000")
                            {
                                yarn += "/" + gacolor.Trim();
                            }
                        }
                        if (count > 1)
                        {
                            yarn += ":" + gakg1 + "kg";
                        }
                        else
                        {
                            yarn = gakg1 + "kg";
                        }
                        exAgent.SetCellValue(12 + rownum * 2, 27, yarn);
                    }
                    #endregion
                }
            }
            catch (Exception ex)
            {
                Tracer.Error(ex.StackTrace, ex);
            }
        }

        private void HideNullRows(int pages)
        {
            try
            {
                exAgent.HideRows((pages + 1) * 25 + 1, 1, 500, 999);
            }
            catch (Exception ex)
            {
                Tracer.Error(ex.StackTrace, ex);
            }
        }

        private void CheckDirectory(string root, string sub, string year, string month, string day)
        {
            try
            {
                string drlocal = root;
                string dr0 = "";

                #region========================LOCAL=====================
                drlocal = Path.Combine(PathHelper.ApplicationPath, @"Report");
                if (!Directory.Exists(drlocal))
                    Directory.CreateDirectory(drlocal);

                drlocal = Path.Combine(drlocal, "Sales");
                if (!Directory.Exists(drlocal))
                    Directory.CreateDirectory(drlocal);
                #endregion
                drlocal = root;
                drlocal = Path.Combine(drlocal, sub);
                if (!Directory.Exists(drlocal))
                    Directory.CreateDirectory(drlocal);
            }
            catch (Exception ex)
            {
                Tracer.Error(ex.StackTrace, ex);
            }
        }

        private string CreateFile(string orderno)
        {
            string filename = "";
            string sheetName = "";
            string Standard = "AB50DOC";
            string filePath = Path.Combine(PathHelper.ApplicationPath, @"Report\QFT\QFTStandard.xls");
            try
            {
                string pwd = "";
                sheetName = orderno;
                exAgent.Open(filePath);
                exAgent.Company = strCompany;
                exAgent.strExcelFile = strExcelFile;
                string newfilename = orderno;
                exAgent.CreateNewSheet(newfilename, Standard, orderno.Replace(".xls", ""), pwd);
                filename = exAgent.FileName;
                FillInEXCEL();
                string localFile = exAgent.FileName;
                exAgent.Save();
                exAgent.Close();
                //System.Diagnostics.Process.Start("EXCEL.EXE", localFile);
            }
            catch (Exception ex)
            {
                Tracer.Error(ex.StackTrace, ex);
            }
            return filename;
        }

        private void LocalFile(string ordernumer)
        {
            DataRow dwABKOPF = dsSource.Tables["ABKOPF"].Rows[0];
            string fileabsname = ordernumer + ".xls";
            string localFile = @"C:\Windows\Temp\" + fileabsname;
            string tempfile = "";
            try
            {
                tempfile = CreateFile(fileabsname);
                localFile = @"C:\IntexReport\Production\" + fileabsname;
                if (System.IO.File.Exists(localFile))
                {
                    System.IO.File.Delete(localFile);
                }
                File.Move(tempfile, localFile);
                System.Diagnostics.Process.Start("EXCEL.EXE", localFile);
            }
            catch (Exception ex)
            {
                Tracer.Error(ex.StackTrace, ex);
            }
            finally
            {
                if (File.Exists(tempfile))
                {
                    File.Delete(tempfile);
                }
            }
        }
    }
}